package com.longxi.tianjintianbao.ui.presenter.work;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.greedao.controller.DataWorkController;
import com.longxi.tianjintianbao.greedao.entity.Work;
import com.longxi.tianjintianbao.listener.AdapterListener;
import com.longxi.tianjintianbao.ui.adapter.multitype.LabelViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.work.WorkLayoutViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.work.IWorkLayoutAtView;
import com.longxi.tianjintianbao.utils.MyUtils;

import java.util.Collections;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

public class WorkLayoutAtPresenter extends BasePresenter<IWorkLayoutAtView> {

    private MultiTypeAdapter adapter;
    private Items items;
    private Intent intent = new Intent();

    public WorkLayoutAtPresenter(BaseActivity context) {
        super(context);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            adapter.register(String.class, new LabelViewBinder());
            adapter.register(Work.class, new WorkLayoutViewBinder(listener));
            getView().getRvContent().setAdapter(adapter);
            helper.attachToRecyclerView(getView().getRvContent());
        }
    }

    public void getWorkList() {
        items = new Items();
        items.add("常用");
        items.addAll(DataWorkController.findWorkCategory(1));

        items.add("工作");
        items.addAll(DataWorkController.findWorkCategory(2));

        items.add("@我");
        items.addAll(DataWorkController.findWorkCategory(3));

        adapter.setItems(items);
        adapter.notifyDataSetChanged();
        mContext.hideLoading();
    }

    public void setBar() {
        mContext.setTvLeft(MyUtils.getString(R.string.me_work));
        mContext.setIvRight(R.mipmap.ic_question);
    }

    AdapterListener listener = new AdapterListener() {
        @Override
        public void onClick(int position) {
            if(items.get(position) instanceof Work){
                Work work = (Work) items.get(position);
                if(work.getIsVisible() == 1){
                    work.setIsVisible(0);
                }else{
                    work.setIsVisible(1);
                }
                DataWorkController.updateWork(work);
            }
        }

        @Override
        public void onDelete(int position) {

        }
    };

    public void onDestroy() {
        sendBroadcast();
        listener = null;
        intent = null;
    }

    /**
     * 发送广播
     */
    public void sendBroadcast(){
        //设置广播的名字（设置Action）
        intent.setAction(AppConst.REFRESH_HOME_FRAGMENT);
        //携带数据
        //intent.putExtra("refreshPatrolCount",true);
        //发送广播（无序广播）
        mContext.sendBroadcast(intent);
    }

    //为RecycleView绑定触摸事件
    ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            //首先回调的方法 返回int表示是否监听该方向
            int dragFlags = ItemTouchHelper.UP|ItemTouchHelper.DOWN;//拖拽
//            int swipeFlags = ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;//侧滑删除
            if(items.get(viewHolder.getAdapterPosition()) instanceof String){
                return 0;
            }

//            return makeMovementFlags(dragFlags,swipeFlags);
            return makeMovementFlags(dragFlags, 0);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            Work work = (Work) items.get(viewHolder.getAdapterPosition());
            int viewHolderPosition = viewHolder.getAdapterPosition();//原位置
            int targetPosition = target.getAdapterPosition();//移动到的位置
            switch (work.getCategory()) {
                case 1:
                    if(!cg(1, 4, targetPosition, viewHolderPosition, 0, work)){
                        return false;
                    }
                    break;
                case 2:
                    if(!cg(6, 16, targetPosition, viewHolderPosition, 5, work)){
                        return false;
                    }
                    break;
                case 3:
                    if(!cg(18, 19, targetPosition, viewHolderPosition, 17, work)){
                        return false;
                    }
                    break;
            }
            //滑动事件
            Collections.swap(items,viewHolder.getAdapterPosition(),target.getAdapterPosition());
            adapter.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());
            return false;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            //侧滑事件
//            items.remove(viewHolder.getAdapterPosition());
//            adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
        }

        @Override
        public boolean isLongPressDragEnabled() {
            //是否可拖拽
            return true;
        }
    });

    /**
     * 移动模块逻辑
     * @param start 模块范围开始
     * @param end 模块范围结束
     * @param targetPosition 移动到的位置
     * @param viewHolderPosition 原来的位置
     * @param subPosition 通过这个来计算出当前位置
     * @param work 模块类型
     * @return
     */
    private boolean cg(int start, int end, int targetPosition, int viewHolderPosition, int subPosition, Work work) {
        if(start > targetPosition || targetPosition > end){
            MyUtils.showToast("不能移出所属类别");
            return false;
        }else{
            mContext.showWaitingDialog("正在修改");
            if(viewHolderPosition > targetPosition){
                DataWorkController.updateSort(work.getCategory(), true, targetPosition - subPosition, viewHolderPosition - subPosition);
            }else{
                DataWorkController.updateSort(work.getCategory(), false, targetPosition - subPosition, viewHolderPosition - subPosition);
            }
            work.setSort(targetPosition - subPosition);
            DataWorkController.updateWork(work);
            mContext.hideWaitingDialog();
            return true;
        }
    }
}
